package com.sunfeng.one;

import com.rabbitmq.client.*;
import util.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Auther: Administrator
 * @Date: 2019/2/26 11:01
 * @Description:
 */
public class RabbitConsumer {
    private static final String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        final Channel channel = ConnectionUtil.getChannel();

        channel.basicQos(64); // 设置客户端最多接收未被 ack 的消息的个数
        final Consumer consumer = new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                System.out.println(" recv message: " + new String(body));
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // multiple 的 true 和 false 代表不同意思
                // true 代表批量应答 channel 上未应答的消息
                // false 只会应答 tag=8 的消息 5,6,7 这三个消息依然不会被确认收到消息应答
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(" recv message: " + new String(message.getBody()));
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        };
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("aaaaaa");
        };

        //autoAck设置为false 可以防止消息不必要的丢失   建议设置为false
        //       channel.basicConsume(QUEUE_NAME, false, deliverCallback, cancelCallback);
      channel.basicConsume(QUEUE_NAME, false, consumer);
        TimeUnit.SECONDS.sleep(2);
        channel.close();

    }
}
